using System;
using System.Net;
using ch.ethz.ssh2.channel;
using System.Threading;
namespace ch.ethz.ssh2
{

    /// <summary> A <code>LocalPortForwarder</code> forwards TCP/IP connections to a local
    /// port via the secure tunnel to another host (which may or may not be identical
    /// to the remote SSH-2 server). Checkout {@link Connection#createLocalPortForwarder(int, String, int)}
    /// on how to create one.
    /// 
    /// </summary>
    /// <author>  Christian Plattner
    /// </author>
    /// <version>  2.50, 03/15/10
    /// </version>
    public class LocalPortForwarder
    {
        internal ChannelManager cm;

        internal System.String host_to_connect;

        internal int port_to_connect;

        internal Thread thread;

        internal LocalAcceptThread lat;

        internal LocalPortForwarder(ChannelManager cm, int local_port, System.String host_to_connect, int port_to_connect)
        {
            this.cm = cm;
            this.host_to_connect = host_to_connect;
            this.port_to_connect = port_to_connect;

            lat = new LocalAcceptThread(cm, local_port, host_to_connect, port_to_connect);
            thread = new Thread(new ThreadStart(lat.Run));
            thread.IsBackground = true;
            thread.Start();
        }

        internal LocalPortForwarder(ChannelManager cm, IPEndPoint addr, System.String host_to_connect, int port_to_connect)
        {
            this.cm = cm;
            this.host_to_connect = host_to_connect;
            this.port_to_connect = port_to_connect;

            thread = new Thread(new ThreadStart(new LocalAcceptThread(cm, addr, host_to_connect, port_to_connect).Run));
            thread.IsBackground = true;
            thread.Start();
        }

        /// <summary> Stop TCP/IP forwarding of newly arriving connections.
        /// 
        /// </summary>
        /// <throws>  IOException </throws>
        public virtual void close()
        {
            lat.stopWorking();
        }
    }
}